package top.went.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.went.db.dao.SolutionDao;
import top.went.db.mapper.SolutionMapper;
import top.went.exception.NotFoundException;
import top.went.exception.ServiceException;
import top.went.pojo.SaleOppEntity;
import top.went.pojo.SolutionEntity;
import top.went.utils.TrackLog;
import top.went.vo.PageEntity;
import top.went.vo.SolutionVo;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class SolutionService {
    @Autowired
    private SolutionDao solutionDao;
    @Autowired
    private SolutionMapper solutionMapper;
    @Autowired
    private SaleOppService saleOppService;

    private static final Map<String,String> map = new HashMap<>();

    static {
        map.put("submitTime","submit_time");
        map.put("tbSaleOppByOppId.tbCustomerByCusId.cusName","cus_name");
        map.put("tbSaleOppByOppId.oppTheme","opp_theme");
    }

    /**
     * 新增解决方案
     * @param solutionEntity
     * @return
     * @throws ServiceException
     */
    public boolean addSolution(SolutionEntity solutionEntity) throws ServiceException {
        try {
            if(solutionEntity.getTbSaleOppByOppId() == null || solutionEntity.getTbSaleOppByOppId().getOppId() == null){
                solutionEntity.setTbSaleOppByOppId(null);
            } else {
                Long oppId = solutionEntity.getTbSaleOppByOppId().getOppId();
                SaleOppEntity saleOppEntity = saleOppService.load(oppId);
                String trackLog = TrackLog.getTrack(saleOppEntity,"方案制定").toString();
                saleOppEntity.setStage("方案制定");
                saleOppEntity.setTrackLog(trackLog);
                saleOppEntity.setStageStartTime(new java.sql.Date(new Date().getTime()));
                saleOppService.modifySaleOpp(saleOppEntity);
            }
            return solutionDao.save(solutionEntity) != null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("新增解决方案失败！");
        }

    }

    /**
     * 修改解决方案
     * @param solutionEntity
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean modifySolution(SolutionEntity solutionEntity) throws NotFoundException, ServiceException {
        SolutionEntity solutionEntity1 = load(solutionEntity.getSolutionId());
        if (solutionEntity1 == null)
            throw new NotFoundException("解决方案未找到！");
        solutionEntity1.setSolutionTheme(solutionEntity.getSolutionTheme());
        solutionEntity1.setSubmitTime(solutionEntity.getSubmitTime());
        solutionEntity1.setSolutionContent(solutionEntity.getSolutionContent());
        solutionEntity1.setCustomerFeedback(solutionEntity.getCustomerFeedback());
        solutionEntity1.setAnnex(solutionEntity.getAnnex());
//        solutionEntity1.setIsDelete(0L);
        if(solutionEntity.getTbSaleOppByOppId() != null && solutionEntity.getTbSaleOppByOppId().getOppId() != null){
            solutionEntity1.setTbSaleOppByOppId(solutionEntity.getTbSaleOppByOppId());
        } else {
            solutionEntity1.setTbSaleOppByOppId(null);
        }
        try {
            solutionDao.save(solutionEntity1);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("编辑方案失败！");
        }
    }

    /**
     * 删除解决方案
     * @param id
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean deleteSolution(Long id) throws NotFoundException, ServiceException {
        SolutionEntity solutionEntity = load(id);
        if (solutionEntity == null)
            throw new NotFoundException("解决方案不存在！");
        solutionEntity.setIsDelete(1L);
        try {
            solutionDao.save(solutionEntity);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("删除解决方案失败！");
        }
    }

    /**
     * 编辑删除
     * @param ids
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean deleteSelected(Long[] ids) throws NotFoundException, ServiceException {
        for(int i=0; i< ids.length; i++){
            deleteSolution(ids[i]);
        }
        return true;
    }

    /**
     * 加载解决方案
     * @param id
     * @return
     * @throws NotFoundException
     */
    public SolutionEntity load(Long id) throws NotFoundException {
        SolutionEntity solutionEntity = solutionDao.findBySolutionIdAndIsDelete(id,0L);
        if(solutionEntity == null){
            throw new NotFoundException("解决方案不存在！");
        }
        return solutionEntity;
    }

    /**
     * 加载所有解决方案
     * @return
     */
    public List<SolutionEntity> loadList(){
        return solutionDao.findAllByIsDelete(0L);
    }

    /**
     * 快速查询解决方案（方案主题）
     * @param pageNumber
     * @param pageSize
     * @param solutionTheme
     * @return
     */
    public PageEntity<SolutionEntity> loadListWhere(Integer pageNumber, Integer pageSize, String solutionTheme){
        PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize);
        List<SolutionEntity> list = solutionDao.findAllByIsDeleteWhere(0L,"%"+solutionTheme+"%",pageRequest);
        PageEntity pageEntity = new PageEntity((long) list.size(),list);
        return pageEntity;
    }

    /**
     * 解决方案高级查询
     * @param pageNumber
     * @param pageSize
     * @param solutionVo
     * @return
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager-my")
    public PageEntity<SolutionEntity> findAllSeniorSearch(Integer pageNumber, Integer pageSize, SolutionVo solutionVo){
        String order = solutionVo.getPage().getSort(map);
        if(order.length() <= 0){
            order = "solution_id desc";
        }
        Page<SolutionEntity> page = PageHelper.startPage(pageNumber, pageSize,order+" nulls last");
        solutionMapper.findAllSeniorSearch(solutionVo);
        return new PageEntity<>(page.getTotal(),page.getResult());
    }
}
